package com.xl.tools;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

/**
 * 南星二维码临时生成
 */
public class NanXingQrCodeUtils {

    public static void main(String[] args) throws IOException {
        String codes = "10012100586_01,10012100595_01,10012100604_01,10012200427_01,20012200035_01,20012200035_02";
        String [] array = codes.split(",");
        for(String pno : array){
            String [] tArray = pno.split("_");
            write(tArray[0],tArray[1]);
        }
    }

    public static void write(String code, String gun)throws IOException {
        FileInputStream logoFile = new FileInputStream(new File("D:/qrtest/295164745776650.png"));
        String dir = "D:/qrtest/testicon/" + code;
        File codeFile = new File(dir.concat("_").concat(gun).concat(".png"));
        String qrUrl = "https://wx.chargeland.cn/qcode?code=" + code;
        String pileNoText = code;
        String gunNoText = gun;
        String title = "【扫一扫】开锁充电";
        drawLogoQRCodeSizeForTemplate(logoFile, codeFile, qrUrl, pileNoText, gunNoText, title);
    }


    public static BufferedImage drawLogoQRCodeSizeForTemplate(InputStream logo, File codeFile, String qrUrl, String pileNoText, String gunNoText, String title) throws IOException {
        int w = 300;
        int h = 450;
        BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);

        Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>() {
            private static final long serialVersionUID = 1L;

            {
                put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);// 设置QR二维码的纠错级别（H为最高级别）具体级别信息
                put(EncodeHintType.CHARACTER_SET, "utf-8");// 设置编码方式
                put(EncodeHintType.MARGIN, 0);
            }
        };

        Graphics2D g2d = image.createGraphics();
        g2d.setPaint(Color.white);

        g2d.fillRect(0, 0, w, h);
        g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        g2d.setPaint(new Color(45, 140, 240));
        g2d.fillRect(0, 0, w, h >> 1);

        Stroke defaultStroke = g2d.getStroke();
        int boxW = 200;
        Rectangle2D.Double rect = new Rectangle2D.Double((w - boxW) >> 1, (h - boxW) >> 1, boxW, boxW);
        //
        g2d.setPaint(new Color(255, 255, 255));
        g2d.fill(rect);

        Stroke stroke = new BasicStroke(3);
        g2d.setPaint(Color.black);
        g2d.setStroke(stroke);
        g2d.draw(rect);

        //微信，支付宝
        String text = "[扫一扫]启动充电";
        if (title != null && !title.trim().equals("")) {
            text = title;
        }
        g2d.setPaint(Color.white);
        g2d.setStroke(defaultStroke);
        g2d.setFont(new Font("楷体", Font.BOLD, 23));
        int textWidth = g2d.getFontMetrics().stringWidth(text);
        g2d.drawString(text, (w - textWidth) >> 1, ((h - boxW - g2d.getFontMetrics().getHeight()) >> 1));
        //
        int qrW = 170;
        int x = (w - qrW) >> 1;
        int y = (h - qrW) >> 1;
        Image qrImage = drawLogoQRCodeNoText(logo, qrUrl);
        g2d.drawImage(qrImage, x, y, qrW, qrW, null);

        String pileNo = "桩编号：" + pileNoText;
        String gunNo = "枪  号：" + gunNoText + " #";

        int tx;
        int ty = 380;
        g2d.setPaint(Color.black);
        Font font = new Font("楷体", Font.BOLD, 16);
        g2d.setFont(font);
        int tw = g2d.getFontMetrics().stringWidth(pileNo);
        tx = (w - tw) >> 1;
        g2d.drawString(pileNo, tx, ty);
        ty += 30;
        g2d.drawString(gunNo, tx, ty);
        try {
            Image wxPayImage = ImageIO.read(NanXingQrCodeUtils.class.getResourceAsStream("/qricon/wxtalk.png"));
            g2d.setPaint(Color.white);
            RoundRectangle2D roundRectangle2D = new RoundRectangle2D.Double((w - boxW) >> 1, 30, 48, 48, 20, 20);
            g2d.fill(roundRectangle2D);
            g2d.drawImage(wxPayImage, (w - boxW) >> 1, 30, 48, 48, null);
            //
            Image aliPayImage = ImageIO.read(NanXingQrCodeUtils.class.getResourceAsStream("/qricon/alipay.png"));
            g2d.setPaint(Color.white);
            roundRectangle2D = new RoundRectangle2D.Double((((h - boxW - 48))), 30, 48, 48, 24, 24);
            g2d.fill(roundRectangle2D);
            g2d.drawImage(aliPayImage, (((h - boxW - 48))), 30, 48, 48, null);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        g2d.dispose();
        image.flush();
        if (codeFile != null) {
            codeFile.getParentFile().mkdirs();
            codeFile.createNewFile();
            ImageIO.write(image, "png", codeFile);
            System.out.println(codeFile.getAbsolutePath());
        }
        return image;
    }


    public static BufferedImage drawLogoQRCodeNoText(InputStream logo, String qrUrl) {
        int w = 170;
        int h = 170;
        BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        int QRCOLOR = 0xFF000000; // 默认是黑色
        int BGWHITE = 0xFFFFFFFF; // 背景颜色
        Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>() {
            private static final long serialVersionUID = 1L;

            {
                put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);// 设置QR二维码的纠错级别（H为最高级别）具体级别信息
                put(EncodeHintType.CHARACTER_SET, "utf-8");// 设置编码方式
                put(EncodeHintType.MARGIN, 0);
            }
        };
        try {
            MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
            // 参数顺序分别为：编码内容，编码类型，生成图片宽度，生成图片高度，设置参数
            BitMatrix bm = multiFormatWriter.encode(qrUrl, BarcodeFormat.QR_CODE, w, h, hints);

            // 开始利用二维码数据创建Bitmap图片，分别设为黑（0xFFFFFFFF）白（0xFF000000）两色
            for (int x = 0; x < w; x++) {
                for (int y = 0; y < h; y++) {
                    image.setRGB(x, y, bm.get(x, y) ? QRCOLOR : BGWHITE);
                }
            }
            Font font = new Font("楷体", Font.BOLD, 20);
            int textHeight = font.getSize();
            // 新的图片，把带logo的二维码下面加上文字
            BufferedImage outImage = new BufferedImage(w + 10, h + 12, BufferedImage.TYPE_4BYTE_ABGR);
            Graphics2D outg = outImage.createGraphics();
            //白色背景
            outg.setPaint(Color.white);
            outg.drawRect(0, 0, outImage.getWidth(), outImage.getHeight());
            outg.fillRect(0, 0, outImage.getWidth(), outImage.getHeight());
            // 画二维码到新的面板
            outg.drawImage(image, 5, 6, image.getWidth(), image.getHeight(), null);
            // 画文字到新的面板
            outg.setColor(Color.BLACK);
            outg.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            outg.dispose();
            outImage.flush();
            image = outImage;
            if (logo != null) {
                // 构建绘图对象
                Graphics2D g = image.createGraphics();
                // 读取Logo图片
                BufferedImage logoImg = ImageIO.read(logo);
                // 开始绘制logo图片
                Rectangle rect = new Rectangle((outImage.getWidth() - logoImg.getWidth()) / 2 - 1, (h + 10 - logoImg.getHeight()) / 2 - 1, logoImg.getWidth() + 2, logoImg.getHeight() + 2);
                g.fillRoundRect(rect.x, rect.y, rect.width, rect.height, 2, 2);
                g.drawImage(logoImg, rect.x + 2, rect.y + 2, 32, 32, null);
                g.dispose();
                logoImg.flush();
            }

            image.flush();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return image;
    }


}
